#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   personcheck.py    
@Contact :   raogx.vip@hotmail.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA

@Modify Time      @Author          @Version    @Desciption
------------      -------------    --------    -----------
2020/3/12 5:31 PM   Weiping Huang      1.0         None
"""
from PIL import Image
from aip import AipBodyAnalysis
# pip install pillow
# pip install baidu-aip

APP_ID = '18381062'
API_KEY = 'yxBPs39DYUUfgjo14zPh81CF'
SECRET_KEY = 'wKKEg7PkLygWoOsswPN55znP2mV6Vrrx'

client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)

# 路径
path_fanart = '/Users/weipinghuang/微力/百度人脸识别/1.jpeg'
path_poster = '/Users/weipinghuang/微力/百度人脸识别/2.jpeg'

# 人体识别，返回鼻子位置
def image_cut(file_name, cli):
    with open(file_name, 'rb') as fp:
        image = fp.read()
    try:
        result = cli.bodyAnalysis(image)
        return int(result["person_info"][0]['body_parts']['nose']['x'])
    except:
        print('    >人体分析出现错误，请对照“人体分析错误表格”：', result)
        print('    >正在尝试重新人体检测...')
        return image_cut(file_name, cli)

def people_check():
    img = Image.open(path_fanart)
    wf, hf = img.size  # fanart的宽 高
    wide = int(hf * 2 / 3)
    wide_half = wide / 2
    x_nose = image_cut(path_fanart, client)  # 鼻子的x坐标  0.704 0.653
    if x_nose + wide_half > wf:  # 鼻子 + 一半poster宽超出fanart右边
        x_left = wf - wide  # 以右边为poster
    elif x_nose - wide_half < 0:  # 鼻子 - 一半poster宽超出fanart左边
        x_left = 0  # 以左边为poster
    else:  # 不会超出poster
        x_left = x_nose - wide_half  # 以鼻子为中心向两边扩展
    # crop
    poster = img.crop((x_left, 0, x_left + wide, hf))
    poster.save(path_poster, quality=95)
    print('    >poster.jpg裁剪成功')

people_check()
